# coding=utf-8

import logging
from flask import render_template, current_app as app, url_for, request
from .signals import password_forgot_signal
from flask_mail import Message
from over.app import mail

logger = logging.getLogger("over.signals")


def sender_email(subject, body, sender, recipients, is_html=False):
    with mail.connect() as conn:
        if is_html:
            message = Message(sender=sender, recipients=recipients, html=body, subject=subject)
        else:
            message = Message(sender=sender, recipients=recipients, body=body, subject=subject)
        conn.send(message)


@password_forgot_signal.connect
def password_forgot(user):
    logger.info("receive user {0} forgot message".format(user.email))
    sender = app.config['MAIL_DEFAULT_SENDER']

    action_url = '%s://%s%s'  %(request.scheme, request.host, url_for('over.handlers.auth.reset_password', code=user.code))

    context = {
        "product_name": app.config['SITE_NAME'],
        'name': user.email,
        "action_url": action_url,
        "sender_name": sender,
    }
    rv = render_template("mail/forgot_password.html", **context)
    subject = u'%s-密码重置' % app.config['MAIL_SITE_NAME']
    sender_email(subject, rv, sender, [user.email], is_html=True)
